package com.example.shengyin.controller;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson2.JSON;
import com.example.shengyin.service.AdminService;
import com.example.shengyin.entity.Page;
import com.example.shengyin.util.Md5Utils;
import com.example.shengyin.util.Result;
import com.example.shengyin.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.example.shengyin.entity.Admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * AdminController
 * 
 * @author ruoyi
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/admin")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
//swagger
@Api(value = "管理员")
//redis缓存用
public class AdminController
{
    @Autowired
    private AdminService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public Result adminLogin(String root, String pass, String code, HttpServletRequest request) {

        System.out.println(code+"================?"+request.getSession().getAttribute("code"));
        if(!code.equals(request.getSession().getAttribute("code"))){
            return Result.error("验证码输入错误");
        }
        Admin login = service.login(root,Md5Utils.hash(pass));
        System.out.println("root:"+root+",pass:"+pass);
        if(login==null)
            return Result.error("错误的用户名或者密码！");
        HttpSession session = request.getSession();
        session.setAttribute("user",login);
        System.out.println("user"+login.toString());
        String key= UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key,login,300, TimeUnit.MINUTES);
        return Result.success(key,"登录成功");


        //return Result.success("登录成功");
    }
    /**
     * 查询Admin列表
     */
    @ApiOperation("分页查询")
    @GetMapping("/list")
    public Result list(Page page,@ApiParam(name = "uname",value = "登录名") @RequestParam(required = false) String uname,
                       @ApiParam(name = "phone",value = "手机号") @RequestParam(required = false) String phone,
                       @ApiParam(name = "realname",value = "真实") @RequestParam(required = false) String realname,
                       @ApiParam(name = "pos",value = "职务") @RequestParam(required = false) String pos,
                       @ApiParam(name = "roles",value = "权限") @RequestParam(required = false) String roles,
                       @ApiParam(name = "starttime",value = "广告发布时间的搜索条件的起始值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required =
                                             false) Date starttime,
                                     @ApiParam(name = "endtime",value = "广告发布时间的搜索条件的结束值")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required =
                                             false) Date endtime,BindingResult bindingResult)
    {
        Timestamp start=StrUtil.toTimestamp(starttime);
        Timestamp end=StrUtil.toTimestamp(endtime);
        System.out.println("page:"+page);
        List<Admin> list = service.list(page,uname,phone,realname,pos,roles,start,end);
        int count = service.count(uname,phone,realname,pos,roles,start,end);
        if(count==0||list==null)
            return Result.success(page,"没有数据");
        page.setData(list);
        page.setCount(count);
        System.out.println(JSON.toJSONString(Result.success(page)));
        return Result.success(page);
    }
    @ApiOperation("单个查找")
    @GetMapping(value = "/select/{id}")
    public Result select(@PathVariable(value = "id") Long id)
    {
        Admin select = service.select(id);
        if(select==null)
            return Result.error("没有找到数据");
        select.setPass(null);
        return Result.success(select);
    }
    @ApiOperation("添加管理员")
    @PostMapping("/add")
    public Result insert(@Valid Admin dAdmin, BindingResult bindingResult, HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }
        int insert = service.insert(dAdmin);
        dAdmin.setPass(Md5Utils.hash(dAdmin.getPass()));
        if(insert==0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }
    @ApiOperation("更新")
    @PostMapping("/edit")
    public Result edit(Admin dAdmin,HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(!(admin.getRoles()==1 ||admin.getId()== dAdmin.getId()))
            return  Result.error("您的权限不足或不是本人操作");
        if(dAdmin.getPass()!=null&&dAdmin.getPass()!="")
        {
            dAdmin.setPass(Md5Utils.hash(dAdmin.getPass()));
        }
        int insert = service.update(dAdmin);
        Admin select = service.select(dAdmin.getId());
        if(insert==0)
            return Result.error("修改失败");
        return Result.success("修改成功");
    }
    @ApiOperation("删除单个")
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable(value = "id")int id,HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
            return  Result.error("您的权限不足");
        int delete = service.delete(id);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }
    @ApiOperation("删除多个")
	@GetMapping("/deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable(value = "ids")String ids,HttpServletRequest request)
    {
        System.out.println(request.getHeader("Authorization"));
        Admin admin = (Admin) redisTemplate.opsForValue().get(request.getHeader("Authorization"));
        if(admin.getRoles()!=1)
        {
            return Result.error("您的权限不足");
        }
        System.out.println("开始这些");
        String s = StrUtil.ListtoString(ids);
        int delete = service.deleteByIds(s);
        if(delete==0)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }
}
